package pl.balon.gwt.diagrams.client.connection.pointwidget;

import pl.balon.gwt.diagrams.client.connection.AbstractConnection;
import pl.balon.gwt.diagrams.client.images.ImageFactory;

import com.google.gwt.event.dom.client.KeyPressEvent;
import com.google.gwt.event.dom.client.KeyPressHandler;
import com.google.gwt.event.shared.HandlerRegistration;
import com.google.gwt.user.client.ui.AbsolutePanel;
import com.google.gwt.user.client.ui.FocusPanel;
import com.google.gwt.user.client.ui.Image;

public class MoveablePointWidgetImpl extends FocusPanel implements MoveablePointWidget{
	private int controledIndexPoint;
	Image image=null;
	private final AbstractConnection connection;
	public MoveablePointWidgetImpl(AbstractConnection connection) {
		super();
		this.connection=connection;
		this.image=ImageFactory.getInstance().createImage("selectablepoint");
		this.add(this.image);
		this.addStyleName("gwt-diagrams-movablepointwidget");
		this.setWidth("10px");
		this.setHeight("10px");
	}

	@Override
	protected void onAttach() {
		super.onAttach();
	}

	/* (non-Javadoc)
	 * @see pl.balon.gwt.diagrams.client.connection.pointwidget.MovablePointWidget#setControledIndexPoint(int)
	 */
	public void setControledIndexPoint(int controledIndexPoint) {
		this.controledIndexPoint = controledIndexPoint;
	}



	/* (non-Javadoc)
	 * @see pl.balon.gwt.diagrams.client.connection.pointwidget.MovablePointWidget#getControledIndexPoint()
	 */
	public int getControledIndexPoint() {
		return controledIndexPoint;
	}




	public enum State{ONMOUSEOVER,FREE}
	public void setState(State state) {
		if(state == State.ONMOUSEOVER)
			ImageFactory.getInstance().applyTo(this.image,"onmouseoverselectablepoint");
		else if(state == State.FREE)
			ImageFactory.getInstance().applyTo(this.image,"selectablepoint");
	}

	public int getLeft() {
		return this.getAbsoluteLeft()-getParent().getAbsoluteLeft()+this.getOffsetWidth()/2;
	}
	public int getTop() {
		return this.getAbsoluteTop()-getParent().getAbsoluteTop()+this.getOffsetHeight()/2;
	}
	int prevLeft, prevTop;
	public void setPosition(int left, int top) {
		prevLeft=left;
		prevTop=top;
		AbsolutePanel panel =  (AbsolutePanel) this.getParent();
		//panel.setWidgetPosition(this, left-this.getOffsetWidth()/2,top-this.getOffsetHeight()/2);
		panel.setWidgetPosition(this, left-this.getOffsetWidth()/2,top-this.getOffsetHeight()/2);
	}

	protected boolean hasMoved() {
		if(prevLeft!=getLeft() && prevTop!=getTop() ) {
			prevLeft=getLeft();
			prevTop=getTop();
			return true;
		}
		return false;
	}

	@Override
	public HandlerRegistration addKeyPressHandler(KeyPressHandler handler) {
		return addDomHandler(handler, KeyPressEvent.getType());
	}

	public AbstractConnection getConnection() {
		return connection;
	}



}
